package com.example.module_home.paging

import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.module_home.Article
import com.example.module_home.WebDetailActivity
import com.example.module_home.databinding.HomeItemPageBinding
import java.text.SimpleDateFormat


val DIFF = object : DiffUtil.ItemCallback<Article>() {
    override fun areItemsTheSame(oldItem: Article, newItem: Article): Boolean {
        return oldItem.author == newItem.author
    }

    override fun areContentsTheSame(oldItem: Article, newItem: Article): Boolean {
        return oldItem == newItem
    }


}


class ArticleViewHolder(private val binding: HomeItemPageBinding) :
    RecyclerView.ViewHolder(binding.root) {


    fun bind(article: Article) {

        val dateFormat = SimpleDateFormat("yyyy-MM-dd")
        binding.tvChapter.text = article.title
        binding.tvAuthor.text = article.author
        binding.tvDate.text = dateFormat.format(article.publishTime)

        binding.root.setOnClickListener {
            binding.root.context.apply {
                startActivity(Intent(this, WebDetailActivity::class.java).apply {
                    putExtra(WebDetailActivity.WEB_URL,article.link)
                })
            }
        }
    }
}

class ArticlePageAdapter : PagingDataAdapter<Article, ArticleViewHolder>(DIFF) {

    override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) {
        getItem(position)?.let { holder.bind(it) }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder {

        val binding =
            HomeItemPageBinding.inflate(LayoutInflater.from(parent.context), parent, false)

        return ArticleViewHolder(binding)

    }


}



